package com.ylkj.timer.task;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.ylkj.timer.bo.ORA_SOURCE;
import com.ylkj.timer.bo.ORA_TARGET;
import com.ylkj.timer.bo.WS_TARGET;
import com.ylkj.timer.service.impl.CommonServiceImpl;
import com.ylkj.timer.webservice.WSServerDelegate;
import com.ylkj.timer.webservice.WSServerService;

/**
 * 智能园区webservice-数据抽取任务
 * @author zjf
 *
 */
public class WebServiceTask {
	private static final Log log = LogFactory.getLog(WebServiceTask.class);
	private static final String NAMESPACE = "com.ylkj.timer.dao";
	private CommonServiceImpl local_commonService;
	public CommonServiceImpl getLocal_commonService() {
		return local_commonService;
	}
	public void setLocal_commonService(CommonServiceImpl localCommonService) {
		local_commonService = localCommonService;
	}
	/**
	 * 每5分钟从源webservice中获取最新数据，可配置
	 */
	public void work1()
	{
		MDC.put("DBTYPE", "2");
		//通过webservice获取定时xml数据
		try {
			WSServerService wSServerService = new WSServerService();
			WSServerDelegate wSServerServicedelegate = wSServerService.getWSServerPort();
			Document doc =DocumentHelper.parseText(wSServerServicedelegate.excute(getSendString("2","1","123456")));
			
			log.debug("定时抽取："+doc.asXML());
			//解析xml数据，获取根元素
			Element root = doc.getRootElement();
			String result = root.attributeValue("RESULT");
			//服务端获取数据异常
			if(result.equals("0"))
			{
				log.debug("webservice服务端返回异常！");
				//从本地获取数据覆盖
				try {
					local_commonService.insert(NAMESPACE, "insertForSelf", new WS_TARGET());
				} catch (Exception e) {
					log.debug("WS 本地插入异常！"+e.getMessage());
				}
			}
			//定时获取数据
			else if(result.equals("2")){
				List<Element> rows = root.elements("ROW");
				if(rows.size()!=1)
				{
					log.debug("webservice 返回异常：数量应为1，实际为："+rows.size());
				}
				else{
					//正常获取到一条最新数据
					List<Element> cols = rows.get(0).elements("COL");
					Element va =  cols.get(0);
					Element elec = cols.get(1);
					Element data_date =  cols.get(2);
					Element cons_id =  cols.get(3);
					WS_TARGET ws_target = new WS_TARGET();
					ws_target.setMark("1");
					ws_target.setVa(Double.parseDouble(va.getText()));
					ws_target.setElec(Double.parseDouble(elec.getText()));
					ws_target.setCons_id(cons_id.getText());
					try {
						SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						ws_target.setData_date(sdf.parse(data_date.getText()));
						local_commonService.insert(NAMESPACE, "insertForWS", ws_target);
					} catch (Exception e) {
						log.debug("WS 本地插入异常！"+e.getMessage());
					}
				}
			}else{
				log.debug("webservice 返回异常状态"+result);
			}
		} catch (Exception e) {
			log.debug("webservice 数据链接异常！"+e.getMessage());
			//从本地获取数据覆盖
			try {
				local_commonService.insert(NAMESPACE, "insertForSelf", new WS_TARGET());
			} catch (Exception e1) {
				log.debug("WS 本地插入异常！"+e1.getMessage());
			}
		}
	}
	/**
	 * 请求xml
	 * @return
	 */
	
	public String getSendString(String type,String num,String cons_id)
	{
		Document doc = DocumentHelper.createDocument();
		Element DBSET = doc.addElement("DBSET");
		Element ROW = DBSET.addElement("ROW");
		Element COL1 = ROW.addElement("COL");
		COL1.addAttribute("NAME", "TYPE");
		COL1.setText(type);
		Element COL2 = ROW.addElement("COL");
		COL2.addAttribute("NAME", "NUM");
		COL2.setText(num);
		Element COL3 = ROW.addElement("COL");
		COL3.addAttribute("NAME", "CONS_ID");
		COL3.setText(cons_id);
		return doc.asXML();
	}
	/**
	 * 每1个小时的定时填补任务，可配置
	 */
	public void work2()
	{
		MDC.put("DBTYPE", "2");
		int count ;
		HashMap hm = new HashMap();
		try {
			//获取到目前需要填补的条数
			List list = local_commonService.getCommonDao().find(NAMESPACE, "queryForWSCount", null);
			hm = (HashMap) list.get(0);
			count = Integer.parseInt(hm.get("COUNT").toString());
			log.debug("填补条数为"+count);
			if(count==0)
			{
				log.debug("无数据需要填补");
			}
			else{
				//根据需要填补的条数去源数据库获取对应数据
				WSServerService wSServerService = new WSServerService();
				WSServerDelegate wSServerServicedelegate = wSServerService.getWSServerPort();
				Document doc =DocumentHelper.parseText(wSServerServicedelegate.excute(getSendString("2",count+"","123456")));
				log.debug("定时填补："+doc.asXML());
				//解析xml数据，获取根元素
				Element root = doc.getRootElement();
				String result = root.attributeValue("RESULT");
				//服务端获取数据异常
				if(result.equals("0"))
				{
					log.debug("webservice-定时填补-服务端返回异常！");
				}
				else if(result.equals("2")){
					//删除并验证
					int deletecount = local_commonService.delete(NAMESPACE, "deleteForWS",null);
					if(deletecount==count)
					{
						List<Element> rows = root.elements("ROW");
						//遍历元素
						WS_TARGET ws_target = new WS_TARGET();
						for(int i=0;i<rows.size();i++)
						{
							List<Element> cols = rows.get(i).elements("COL");
							Element va =  cols.get(0);
							Element elec = cols.get(1);
							Element data_date =  cols.get(2);
							Element cons_id =  cols.get(3);
							
							ws_target.setMark("1");
							ws_target.setVa(Double.parseDouble(va.getText()));
							ws_target.setElec(Double.parseDouble(elec.getText()));
							ws_target.setCons_id(cons_id.getText());
							SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							ws_target.setData_date(sdf.parse(data_date.getText()));
							try {
								local_commonService.insert(NAMESPACE, "insertForWS", ws_target);
							} catch (Exception e) {
								log.debug("WS 本地插入异常！"+e.getMessage());
							}
						}
					}
					else{
						log.debug("删除数量不一致"+"删除数量："+deletecount+" 需填补数量"+count);
					}
				}
			}
		} catch (Exception e) {
			log.debug("webservice 定时填补执行异常"+e.getMessage());
		}
	}
}
